<?php
/**
 * 后台内容模型管理模型
 * CmsModelField.php
 * ==============================================
 * 版权所有 2013-2014
 * ----------------------------------------------
 * 这不是一个自由软件，未经授权不许任何使用和传播。
 * ----------------------------------------------
 * 
 * @package xcs
 * @author Huangdaohai <huangdaohai.2007@163.com>
 * @version $Id$
 * @access public
 */
class CmsModelField extends AdminModel
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return AdminCmsModelField the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{cms_model_field}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('field, field_name, field_type, form_type, issystem, isnull, disable', 'required'),
			array('model_id, min_length, max_length, issystem, isnull, disable, sort', 'numerical', 'integerOnly'=>true),
			array('field, field_name, field_type, form_type', 'length', 'max'=>30),
			array('pattern', 'length', 'max'=>255),
			array('setting', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('field_id, model_id, field, field_name, field_type, form_type, setting, min_length, max_length, pattern, issystem, isnull, disable, sort', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}
    /**
	 * 获取菜单列表
	 *
	 * @param array $params
	 * @return array 数据数组和分页对象
	 */
	public function getList($params){
	   $criteria = new CDbCriteria();
        if( !empty( $params ) && is_array($params) && $params ){
            foreach($params as $sKey=>$sVal){
                $criteria->addCondition($sKey.'='.$sVal);
            }
        }
        $criteria->order = 'sort ASC ,field_id ASC' ;//排序条件 
		$oResult = self::model()->findAll($criteria);
		$aList = array();
		if(!empty($oResult)){
			foreach ($oResult as $iKey => $aVal){
				$aList[$aVal->field]['field_id'] = $aVal->field_id;
                $aList[$aVal->field]['model_id'] = $aVal->model_id;
                $aList[$aVal->field]['field'] = $aVal->field;
                $aList[$aVal->field]['field_name'] = $aVal->field_name;
                $aList[$aVal->field]['field_type'] = $aVal->field_type;
                $aList[$aVal->field]['form_type'] = $aVal->form_type;
                $aList[$aVal->field]['setting'] = $aVal->setting;
				$aList[$aVal->field]['min_length'] = $aVal->min_length;
                $aList[$aVal->field]['max_length'] = $aVal->max_length;
                $aList[$aVal->field]['pattern'] = $aVal->pattern;
                $aList[$aVal->field]['issystem'] = $aVal->issystem;
                $aList[$aVal->field]['isnull'] = $aVal->isnull;
                $aList[$aVal->field]['disable'] = $aVal->disable;
                $aList[$aVal->field]['isshow'] = $aVal->isshow;
                $aList[$aVal->field]['sort'] = $aVal->sort;
			}
		}
		//$listResult['list'] = $aList;
		return $aList;
	}
    
    /**
     * CmsModelField::alterTableAddField() 添加表字段
     * 
     * @param mixed $fieldtype
     * @return void
     */
    public function alterTableAddField($params){
        $tablename = isset($params['tablename']) ? $params['tablename'] : '';
        $fieldtype = isset($params['fieldtype']) ? $params['fieldtype'] : 'text';
        $field = isset($params['field']) ? $params['field'] : '';
        $maxlength = isset($params['maxlength']) ? $params['maxlength'] : '';
        $defaultvalue = isset($params['defaultvalue']) ? $params['defaultvalue'] : '';
        //正整数 UNSIGNED && SIGNED
        $minnumber = isset($params['minnumber']) ? $params['minnumber'] : 1;
        $decimaldigits = isset($params['decimaldigits']) ? $params['decimaldigits'] : '';
        switch($fieldtype) {
        	case 'varchar':
        		if(!$maxlength) $maxlength = 255;
        		$maxlength = min($maxlength, 255);
        		$sql = "ALTER TABLE `$tablename` ADD `$field` VARCHAR( $maxlength ) NOT NULL DEFAULT '$defaultvalue'";
                Yii::app()->db->createCommand($sql)->execute();
        	break;
        
        	case 'tinyint':
        		if(!$maxlength) $maxlength = 3;
        		$minnumber = intval($minnumber);
        		$defaultvalue = intval($defaultvalue);
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` ADD `$field` TINYINT( $maxlength ) ".($minnumber >= 0 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$defaultvalue'")->execute();
        	break;
        	
        	case 'number':
        		$minnumber = intval($minnumber);
        		$defaultvalue = $decimaldigits == 0 ? intval($defaultvalue) : floatval($defaultvalue);
        		$sql = "ALTER TABLE `$tablename` ADD `$field` ".($decimaldigits == 0 ? 'INT' : 'FLOAT')." ".($minnumber >= 0 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$defaultvalue'";
                Yii::app()->db->createCommand($sql)->execute();
        	break;
        
        	case 'smallint':
        		$minnumber = intval($minnumber);
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` ADD `$field` SMALLINT ".($minnumber >= 0 ? 'UNSIGNED' : '')." NOT NULL")->execute();
        	break;
        
        	case 'int':
        		$minnumber = intval($minnumber);
        		$defaultvalue = intval($defaultvalue);
        		$sql = "ALTER TABLE `$tablename` ADD `$field` INT ".($minnumber >= 0 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$defaultvalue'";
        		Yii::app()->db->createCommand($sql)->execute();
        	break;
        
        	case 'mediumint':
        		$minnumber = intval($minnumber);
        		$defaultvalue = intval($defaultvalue);
        		$sql = "ALTER TABLE `$tablename` ADD `$field` INT ".($minnumber >= 0 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$defaultvalue'";
                Yii::app()->db->createCommand($sql)->execute();
        	break;
        
        	case 'mediumtext':
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` ADD `$field` MEDIUMTEXT NOT NULL")->execute();                
        	break;
        	
        	case 'text':
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` ADD `$field` TEXT NOT NULL")->execute();
        	break;
        
        	case 'date':
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` ADD `$field` DATE NULL")->execute();
        	break;
        	
        	case 'datetime':
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` ADD `$field` DATETIME NULL")->execute();
        	break;
        	
        	case 'timestamp':
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` ADD `$field` TIMESTAMP NOT NULL")->execute();
        	break;
        }
    }
    /**
     * CmsModelField::alterTableEditField() 修改表字段
     * 
     * @param mixed $params
     * @return void
     */
    public function alterTableEditField($params){
        $tablename = isset($params['tablename']) ? $params['tablename'] : '';
        $fieldtype = isset($params['fieldtype']) ? $params['fieldtype'] : 'text';
        $field = isset($params['field']) ? $params['field'] : '';
        $maxlength = isset($params['maxlength']) ? $params['maxlength'] : '';
        $defaultvalue = isset($params['defaultvalue']) ? $params['defaultvalue'] : '';
        //正整数 UNSIGNED && SIGNED
        $minnumber = isset($params['minnumber']) ? $params['minnumber'] : 1;
        $decimaldigits = isset($params['decimaldigits']) ? $params['decimaldigits'] : '';
        $oldfield = isset($params['oldfield']) ? $params['oldfield'] : $fieldtype;
        switch($fieldtype) {
        	case 'varchar':
        		if(!$maxlength) $maxlength = 255;
        		$maxlength = min($maxlength, 255);
        		$sql = "ALTER TABLE `$tablename` CHANGE `$oldfield` `$field` $fieldtype( $maxlength ) NOT NULL DEFAULT '$defaultvalue'";
        		Yii::app()->db->createCommand($sql)->execute();
        	break;
        
        	case 'tinyint':
        		$minnumber = intval($minnumber);
        		$defaultvalue = intval($defaultvalue);
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` CHANGE `$oldfield` `$field` TINYINT ".($minnumber >= 0 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$defaultvalue'")->execute();
        	break;
        
        	case 'number':
        		$minnumber = intval($minnumber);
        		$defaultvalue = $decimaldigits == 0 ? intval($defaultvalue) : floatval($defaultvalue);
        		$sql = "ALTER TABLE `$tablename` CHANGE `$oldfield` `$field` ".($decimaldigits == 0 ? 'INT' : 'FLOAT')." ".($minnumber >= 0 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$defaultvalue'";
        		Yii::app()->db->createCommand($sql)->execute();
        	break;
        
        	case 'smallint':
        		$minnumber = intval($minnumber);
        		$defaultvalue = intval($defaultvalue);
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` CHANGE `$oldfield` `$field` SMALLINT ".($minnumber >= 0 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$defaultvalue'")->execute();
        	break;
        
        	case 'mediumint':
        		$minnumber = intval($minnumber);
        		$defaultvalue = intval($defaultvalue);
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` CHANGE `$oldfield` `$field` MEDIUMINT ".($minnumber >= 0 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$defaultvalue'")->execute();
        	break;
        
        
        	case 'int':
        		$minnumber = intval($minnumber);
        		$defaultvalue = intval($defaultvalue);
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` CHANGE `$oldfield` `$field` INT ".($minnumber >= 0 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$defaultvalue'")->execute();
        	break;
        
        	case 'mediumtext':
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` CHANGE `$oldfield` `$field` MEDIUMTEXT NOT NULL")->execute();
        	break;
        	
        	case 'text':
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` CHANGE `$oldfield` `$field` TEXT NOT NULL")->execute();
        	break;
        
        	case 'date':
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` CHANGE `$oldfield` `$field` DATE NULL")->execute();
        	break;
        	
        	case 'datetime':
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` CHANGE `$oldfield` `$field` DATETIME NULL")->execute();
        	break;
        	
        	case 'timestamp':
        		Yii::app()->db->createCommand("ALTER TABLE `$tablename` CHANGE `$oldfield` `$field` TIMESTAMP NOT NULL")->execute();
        	break;
        
        }
    }
    
    /**
     * CmsModel::saveData() 保存数据
     * 
     * @param array $attributes 属性数组
     * @param bool $isverify 是否验证
     * @return mix 保存成功返回 主键ID  失败返回错误数组
     */
    public function saveData($attributes ,$isverify=true){
        $this->attributes=$attributes;
        if( $isverify ){
            if( $this->save() ){
                //保存成功             
                return $this->model_id;
            } else {
                return $this->errors;
            }
        } else {
            $this->save(false);
            return $this->model_id;
        }
        
    }
	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'field_id' => 'fieldid',
			'model_id' => '模型',
			'field' => '字段名',
			'field_name' => '字段别名',
			'field_type' => '字段类型',
			'form_type' => '表单类型',
			'setting' => '设置',
            'length' => '字符长度范围',
			'min_length' => '最小长度',
			'max_length' => '最大长度',
			'pattern' => '验证规则',
			'issystem' => '系统',
			'isnull' => '必填',
			'disable' => '禁用',
			'sort' => '排序'
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('field_id',$this->field_id);
		$criteria->compare('model_id',$this->model_id);
		$criteria->compare('field',$this->field,true);
		$criteria->compare('field_name',$this->field_name,true);
		$criteria->compare('field_type',$this->field_type,true);
		$criteria->compare('form_type',$this->form_type,true);
		$criteria->compare('setting',$this->setting,true);
		$criteria->compare('min_length',$this->min_length);
		$criteria->compare('max_length',$this->max_length);
		$criteria->compare('pattern',$this->pattern,true);
		$criteria->compare('issystem',$this->issystem);
		$criteria->compare('isnull',$this->isnull);
		$criteria->compare('disable',$this->disable);
		$criteria->compare('sort',$this->sort);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}